package com.xiaoshuidi.cloud.module.report.xxljob;

import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.report.constant.ContractNodeEnum;
import com.xiaoshuidi.cloud.module.report.constant.ContractStatusEnum;
import com.xiaoshuidi.cloud.module.report.constant.DictionaryEnum;
import com.xiaoshuidi.cloud.module.report.constant.RentStatusEnum;
import com.xiaoshuidi.cloud.module.report.dal.DO.DictDataDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportSalesControlDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.*;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportSalesControlMapper;
import com.xiaoshuidi.cloud.module.report.utils.DateUtils;
import com.xiaoshuidi.cloud.module.report.xxljob.PO.ApartmentPO;
import com.xiaoshuidi.cloud.module.report.xxljob.PO.ContractRoomPO;
import com.xiaoshuidi.cloud.module.report.xxljob.PO.RoomStateRecordPO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 销控表job每天2点30
 * 由于此表变动 受房态，房源编辑（房间本价）,合同签约，结束等影响，无法将数据汇聚一处,所以此处采用房源全量跑批形式
 */
@Component
@Slf4j
public class ReportSalesControlHandleJob {

    @Resource
    private ReportSalesControlMapper reportSalesControlMapper;

    @Resource
    private ApartmentMapper apartmentMapper;
    @Resource
    private RoomStateRecordMapper roomStateRecordMapper;
    @Resource
    private ContractRoomMapper contractRoomMapper;
    @Resource
    private SystemDictDataMapper systemDictDataMapper;

    @XxlJob("reportSalesControlHandleJob")
    @TenantIgnore
    public void execute() {
        //获取所有销控表数据 分2000批次处理
        //分2000 一批次处理
        int pageNo = 0;
        int pageSize = 500;
        List<ReportSalesControlDO> list;
        do {
            int from = pageNo * pageSize;
            list = reportSalesControlMapper.selectAllSaleControlByPage(from, pageSize);
            handleLedgerList(list);
            pageNo++;
        } while (list.size() == 500);
    }


    private void handleLedgerList(List<ReportSalesControlDO> list) {
        //待处理字段门店名称 房屋状态 预定状态 是否空置，空置时间 每天可能改变 需日同步一次
        List<Long> apartmentIds = list.stream().map(ReportSalesControlDO::getApartmentId).collect(Collectors.toList());
        List<ApartmentPO> apartmentList = apartmentMapper.selectBatchByIds(apartmentIds);
        List<Long> roomIds = list.stream().map(ReportSalesControlDO::getId).collect(Collectors.toList());
        List<RoomStateRecordPO> roomStateList = roomStateRecordMapper.selectBatchByRoomIds(roomIds);
        List<DictDataDO>  towardList = systemDictDataMapper.getDictMapByType(DictionaryEnum.ROOMS_TOWARD.getCode());
        Map<String, String> towardMap = towardList.stream().collect(Collectors.toMap(DictDataDO::getValue, DictDataDO::getLabel));
        LocalDate now = LocalDate.now();
        for (ReportSalesControlDO controlDO : list) {
            controlDO.setHandleFlag(1);
            try {
                if(StringUtils.isNotBlank(controlDO.getToward())&& Arrays.asList("1","2","3","4","5","6","7","8").contains(controlDO.getToward())){
                    //将朝向从字典翻译，方便查询导出
                    controlDO.setToward(towardMap.get(controlDO.getToward()));
                }
                apartmentList.forEach(apartmentPO -> {
                    if (apartmentPO.getId().equals(controlDO.getApartmentId())) {
                        controlDO.setApartmentName(apartmentPO.getName());
                        return;
                    }
                });
                //预定态和房态 房源存逻辑和报表展示逻辑有区别
                roomStateList.forEach(roomState -> {
                    if (roomState.getRoomId().equals(controlDO.getId())) {
                        if (RentStatusEnum.SCHEDULED.getValue().equals(roomState.getState())) {
                            controlDO.setBookStatus("是");
                        } else {
                            controlDO.setRoomStatus(RentStatusEnum.getName(roomState.getState()));
                            controlDO.setBookStatus("否");
                        }
                    }
                    return;
                });
                ContractRoomPO contractRoomPO = contractRoomMapper.selectOneByContractStatus(controlDO.getId());
                if(contractRoomPO==null){
                    //无生效的合同直接算空出
                    controlDO.setVacantFlag("是");
                    controlDO.setVacantDate(null);
                }else {
                    if(ContractStatusEnum.ACTIVE.getStatus().equals(contractRoomPO.getContractStatus())||ContractStatusEnum.CHECK_IN.getStatus().equals(contractRoomPO.getContractStatus())){
                        //合同生效或入住 如果合同开始时间是在10天内 则需判断 合同结束时间是否超过10天
                        if(DateUtils.getDaySpace(now, contractRoomPO.getStartTime()) <= 10) {
                            //开始时间10天内 且结束时间10天内算空出
                            if(DateUtils.getDaySpace(now, contractRoomPO.getEndTime()) <= 10){
                                controlDO.setVacantFlag("是");
                                controlDO.setVacantDate(contractRoomPO.getEndTime().plusDays(1));
                            }else {
                                //开始时间10天内 且结束时间超过10天不算空出
                                controlDO.setVacantFlag("否");
                                controlDO.setVacantDate(null);
                            }
                        }else {
                            //合同开始时间在10天后 先判断是否是续租合同，如果是续租合同，看看当前是否有正在入住的合同
                            // 算空出 需从上份合同获取结束时间
                            if(ContractNodeEnum.RENEWAL.getNode().equals(contractRoomPO.getContractNode())){
                                controlDO.setVacantFlag("否");
                                controlDO.setVacantDate(null);
                            }else {
                                ContractRoomPO contractRoomPO1 = contractRoomMapper.selectOneByStatusEnd(controlDO.getId());
                                if(contractRoomPO1!=null){
                                    controlDO.setVacantFlag("是");
                                    controlDO.setVacantDate(contractRoomPO1.getActualEndTime().plusDays(1));
                                }
                            }

                        }
                    }else {
                        //合同已经结束 直接算空出
                        controlDO.setVacantFlag("是");
                        controlDO.setVacantDate(contractRoomPO.getActualEndTime().plusDays(1));
                    }
                }
            } catch (Exception e) {
                log.error("======销控表数据处理异常===== id:{}",controlDO.getId());
                e.printStackTrace();
            }
        }
        reportSalesControlMapper.updateList(list);
    }

}
